#include "BieuThuc.h"
void BieuThuc::BienDoiHauTo()
{
	m_TrungTo.insert(0,"(");
	m_TrungTo.insert(m_TrungTo.size(),")");
	char w,a;
	string temp;
	for(unsigned int i = 0; i <m_TrungTo.size(); ++i) {	
		if(m_bValid) {
			a = m_TrungTo[i];
			if (a >= '0' && a <= '9') {
				temp = a;
				if (i>0 && ((m_TrungTo[i-1] >= '0' && m_TrungTo[i-1] <= '9') || m_TrungTo[i-1] == '.'))
				{}
				else 
					if (m_HauTo.length()>0)
						temp = " " + temp;
				m_HauTo = m_HauTo + temp;
			}
			else if (a == '+' || a == '-' || a == '*' || a == '/') {
				while(stack1.size() && SoSanh(stack1.top(),a)) {
					w = stack1.top();
					stack1.pop();
					temp = w;
					temp = " " + temp;
					m_HauTo += temp;
				}
				stack1.push(a);
				}
			else if(a == '(')
				stack1.push(a);
			else if(a == ')') {
				while(stack1.top() != '(' && stack1.size()) {
					w = stack1.top();
					stack1.pop();
					temp = w;
					temp = " " + temp;
					m_HauTo += temp;
				}
				if (stack1.top() == NULL) {
					m_bValid = 0;
					break;
				}
				stack1.pop();
			}
			else if(a == '.') {
				temp = a;
				m_HauTo += temp;
			}
		}
		else 
			break;
	}
	if(stack1.size())
		m_bValid = 0;
}
void BieuThuc::tinhKQ()
{
	stack1.
	string s,sdd;
	char x2;
	for (unsigned int i = 0; i < m_HauTo.size(); ++i) {
		x2 = m_HauTo[i];
		if(m_HauTo[i] != ' ' && m_HauTo[i] != '+' && m_HauTo[i] != '-' 
			&& m_HauTo[i] != '*' && m_HauTo[i] != '/') {
			x2 = m_HauTo[i];
			s += x2;
		}
		else if (m_HauTo[i] == ' ') {
			if (s.length() > 0) {
				float number = ChuoiThanhSo(s);
				stack2.push(number);
			}
			s = "";
		}
		else {
			float a1,a2,a3;
			if (stack2.size())
				a1 = stack2.top();
			else {
				m_bValid = 0;
				break;
			}
			stack2.pop();
			if (stack2.size())
				a2 = stack2.top();
			else {
				m_bValid = 0;
				break;
			}
			stack2.pop();
			if (m_HauTo[i] == '+')
				a3 = a1 + a2;
			else if (m_HauTo[i] == '-')
				a3 = a2 - a1;
			else if (m_HauTo[i] == '*')
				a3 = a1 * a2;
			else if (m_HauTo[i] == '/')
				a3 = a2 / a1;
			stack2.push(a3);
		}
	}
	if(stack2.size() > 1)
		m_bValid = 0;
	if (m_bValid && stack2.size())
		m_fKQ = stack2.top();
}
bool SoSanh(char a, char b)
{
	if(a == '*' || a == '/')
		return 1;
	if(a == '+' || a == '-') {
		if ((b=='*')||(b=='/'))
			return 0;
		return 1;
	}
	return 0;
}
float ChuoiThanhSo(string s)
{
	/*unsigned int i = 0;
	while (s[i] != '.' && i < s.length())
		i++;
	//Xu ly phan so nguyen
	int kq1 = 0;
	for (unsigned int k = 0; k < i; ++k)
		kq1 = kq1*10 + s[k] - 48;
	i++;
	//Xy ly phan thap phan
	float kq2 = 0;
	int mu = 10;
	for (unsigned int j = i; j < s.length(); j++) {
		kq2 = kq2 + (float(s[j] - 48))/mu;
		mu = mu * 10;
	}
	float kq = kq1 + kq2;
	return kq;*/
	
	std::string a=s;
	std::istringstream b(a);
	float f;
	b >> f;
	return f;
}
